#include "articlefetcher.h"
#include "article.h"

#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QUrl>
#include <QByteArray>
#include <QDebug>
#include <QEventLoop>

ArticleFetcher::ArticleFetcher(QObject *parent)
    : QObject{parent}, isSync(false)
{
    // 初始化 QNetworkAccessManager
    httpManager = new QNetworkAccessManager(this);
    connect(httpManager, &QNetworkAccessManager::finished, this, &ArticleFetcher::onRequestFinished);
}

void ArticleFetcher::setSyncMode(bool sync)
{
    isSync = sync;
}

void ArticleFetcher::fetchArticleById(uint articleID) {
    // 设置 API URL
    QUrl url(QString(article_backend + "/api/article/id/%1").arg(articleID));
    QNetworkRequest request(url);

    // 发送 GET 请求
    QNetworkReply* reply = httpManager->get(request);

    // 如果是同步请求，等待请求完成
    if (isSync) {
        QEventLoop loop;
        connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
        loop.exec();
    }
}

void ArticleFetcher::onRequestFinished(QNetworkReply *reply) {
    // 处理响应
    if (reply->error() == QNetworkReply::NoError) {
        QByteArray response = reply->readAll();
        QJsonDocument doc = QJsonDocument::fromJson(response);
        if (doc.isObject()) {
            emit articleFetched(doc.object());
        } else {
            emit fetchFailed("Invalid response format");
        }
    } else {
        emit fetchFailed(reply->errorString());
    }
    reply->deleteLater();
}
